import React, { useEffect, useState } from "react";
import { Button, Table, message, Popconfirm, Select } from "antd";
import {
  listProducts,
  createProduct,
  updateProduct,
  deleteProduct,
  listCategories,
  listWarehouses,
} from "../../api/ckgl";
import ProductModal from "./componets/ProductModal";
const { Option } = Select;

const ListProducts = () => {
  const [productList, setProductList] = useState<any[]>([]);
  const [totalProducts, setTotalProducts] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(10);
  const [isProductModalVisible, setIsProductModalVisible] = useState(false);
  const [currentProduct, setCurrentProduct] = useState<any | null>(null);
  const [categoryList, setCategoryList] = useState<any[]>([]);
  const [warehouses, setWarehouses] = useState<any[]>([]);
  const [warehouseId, setWarehouseId] = useState<number | undefined>(undefined);

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "物品名称",
      dataIndex: "product_name",
      key: "product_name",
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "分类名称",
      dataIndex: "category_name",
      key: "category_name",
      render: (_: any, record: any) => <>{record.category.category_name}</>,
    },
    //   int32 type = 3; // 1-耗材, 2-非耗材
    {
      title: "类型",
      dataIndex: "type",
      key: "type",
      render: (_: any, record: any) => (
        <>{["", "耗材", "非耗材"][record.category.type]}</>
      ),
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      render: (_: any, record: any) => (
        <>
          <Button type="link" onClick={() => handleEditProduct(record)}>
            编辑商品
          </Button>
          <Popconfirm
            okText="确定"
            cancelText="取消"
            title="确定删除物品"
            onConfirm={() => handleDeleteProduct(record)}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  const handleDeleteProduct = (record: any) => {
    // 调用 deleteProduct API，并处理响应
    deleteProduct({
      product_id: record.id,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      message.success(`商品 "${record.product_name}" 删除成功`);
      // 更新当前页
      reset(currentPage);
    });
  };

  const handleEditProduct = (record: any) => {
    setCurrentProduct(record);
    setIsProductModalVisible(true);
  };

  const getListProducts = (page: number) => {
    // 调用 listProducts API，并处理响应
    listProducts({
      page,
      size: pageSize,
      warehouse_id: warehouseId,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      const { products, total } = res.data;
      setProductList(products);
      setTotalProducts(total);
    });
  };

  const reset = (page: number) => {
    getListProducts(page);
  };

  const handleProductModalOk = async (values: any) => {
    // 根据情况调用 createProduct 或 updateProduct API，并处理响应
    if (currentProduct) {
      // 更新
      let msg = "更新成功";
      await updateProduct({
        product_id: currentProduct.id,
        ...values,
      }).then((res: any) => {
        if (res?.code !== 0) {
          message.error(res?.msg || "更新失败");
          return;
        }
        message.success(msg);
      });
    } else {
      // 添加
      let msg = "添加成功";
      await createProduct({
        ...values,
      }).then((res: any) => {
        if (res?.code !== 0) {
          message.error(res.msg);
          return;
        }
        message.success(msg);
      });
    }
    reset(currentPage);
    setIsProductModalVisible(false);
  };

  useEffect(() => {
    !categoryList.length && getListCategories();
    !warehouses.length && getListWarehouses();
    getListProducts(currentPage);
  }, [currentPage, warehouseId]);

  const getListCategories = () => {
    // 调用 listCategories API，并处理响应
    listCategories({
      page: 1,
      size: 300,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      const { categories } = res.data;
      setCategoryList(categories);
    });
  };

  const getListWarehouses = () => {
    // 调用 listSuppliers API，并处理响应
    listWarehouses({
      page: 1,
      size: 300,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      setWarehouses(res.data?.warehouses || []);
    });
  };

  return (
    <div>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
        }}
      >
        <Select
          placeholder="请选择仓库"
          allowClear
          onChange={(value: number) => {
            setWarehouseId(value);
          }}
          style={{
            width: 200,
          }}
        >
          {warehouses.map((role) => (
            <Option key={role.id} value={role.id}>
              {role.warehouse_name}
            </Option>
          ))}
        </Select>
        <Button
          style={{ marginTop: "7px", marginLeft: "10px" }}
          onClick={() => {
            setIsProductModalVisible(true);
            setCurrentProduct(null);
          }}
          size="large"
          type="primary"
        >
          添加商品
        </Button>
      </div>
      <Table
        dataSource={productList}
        columns={columns}
        rowKey="id"
        pagination={{
          pageSize,
          defaultCurrent: 1,
          onChange: setCurrentPage,
          total: totalProducts,
        }}
      />
      <ProductModal
        categoryList={categoryList}
        title={currentProduct ? "编辑商品" : "添加商品"}
        visible={isProductModalVisible}
        onCancel={() => setIsProductModalVisible(false)}
        onOk={handleProductModalOk}
        defaultValue={
          {
            product_name: currentProduct?.product_name || "",
            category_id: currentProduct?.category?.id || "",
          } || {}
        }
      />
    </div>
  );
};

export default ListProducts;
